import React,{useEffect,useState} from 'react'
import { Button, Card,Table,Popconfirm,Tooltip,message } from "antd";
import {delOne, essayApi} from '../../../services/messages'


const Essay = (props) => {
  console.log(props);
  //定义局部状态
  const [dataSource,setDatasource] = useState([]);
  const [total,setTotal] = useState(0);

  useEffect(()=>{
    essayApi()
    .then(res=>{
      console.log(res);
      setDatasource(res.data)
    })
  },[])

  //重新加载页面的方法
  const loadData =page=>{
    essayApi(page).then(res => {
      setDatasource(res.data)
      setTotal(res.totalCount)
    })
  }


  //组件初始化的时候执行
  const columns = [{
    title:'序号',
    key:'id',
    width:80,
    align:'center',
    dataIndex:'id'
  },{
    title:'题目',
    width:160,
    dataIndex:'essay_title',
    align:'center'
  },{
    title:'文章图片',
    width:100,
    dataIndex:'essay_img',
  },{
    title:'文章内容',
    dataIndex:'essay_txt',
    onCell: ()=>{
      return {
        style:{
          maxWidth: 100,
          overflow: 'hidden',
          whiteSpace: 'nowrap',
          textOverflow: 'ellipsis',
          cursor: 'pointer'
        }
      }
    },
    render: (text)=><Tooltip placement="topLeft" title={text}>{text}</Tooltip>
  },{
    title:'操作',
    width:160,
    render:(txt,record,index)=>{
      return(<div>
        <Button type="primary" size='small' onClick={()=>{
          //跳转到编辑页面，传递id作为参数
          props.history.push(`/admin/messages/essayedit/${record.id}`)
        }}>修改</Button>
        <Popconfirm 
          title='确定删除此项？' 
          okText='Yes'
          onCancel={()=>message.info('用户取消删除')} 
          onConfirm={()=>{delOne(record.id).then(res=>{
            loadData(1);
            message.info('删除成功')
          })
        }}>
          <Button  style={{margin:'0 1rem'}}type="primary" danger size='small'>删除</Button>
        </Popconfirm>
        
      </div>)
    }
  }]
  return (
    <Card 
      title='文章列表' 
      extra={
        <Button type="primary" size='small' onClick={()=>props.history.push('/admin/messages/essayedit')}>
          新增
        </Button>
      }>
      <Table 
        columns={columns} 
        bordered 
        dataSource={dataSource} 
        rowKey='id'
        pagination={{total,defaultPageSize:3}}
        />
    </Card>
  )
}

export default Essay